import akshare as ak
import pandas as pd

def process_data(indicator):
    """获取并处理资金流数据"""
    try:
        df = ak.stock_sector_fund_flow_rank(indicator=indicator, sector_type="行业资金流")
        #print(df)
        #print(df.columns)

        # raw = ak.stock_sector_fund_flow_rank(
        #     indicator=indicator,
        #     sector_type="行业资金流"
        # )


        df = df.rename(columns={'名称': '板块名称'})
        #print(df.columns)
        df['资金净流入(亿)'] = df[f'{indicator}主力净流入-净额'] / 100000000  # 转换为“亿”
        df['资金净流入(亿)'] = df['资金净流入(亿)'].round(2)  # 保留两位小数
        df['涨跌幅'] = pd.to_numeric(df[f'{indicator}涨跌幅'], errors='coerce')
        df['流向强度'] = abs(df['资金净流入(亿)'])
        return df.dropna(subset=['资金净流入(亿)'])
    except Exception as e:
        print(f"数据获取失败: {e}")
        return pd.DataFrame()

import plotly.express as px

COLOR_SCALE = [
    [0.0, "#00ff00"],  # 绿色（流出最大）
    [0.45, "#dfffdf"], # 浅绿色（小幅流出）
    [0.5, "#ffffff"],  # 白色（平衡点）
    [0.55, "#ffe5e5"], # 浅红色（小幅流入）
    [1.0, "#ff0000"]   # 红色（流入最大）
]

def generate_heatmap(df):
    """生成树状热力图"""
    fig = px.treemap(
        df,
        path=['板块名称'],
        values='流向强度',
        color='资金净流入(亿)',
        color_continuous_scale=COLOR_SCALE,
        hover_data={
            '涨跌幅': ':%',
            '资金净流入(亿)': ':'
        },
        height=800
    )
    return fig

import streamlit as st
from datetime import datetime

def sidebar_controls():
    with st.sidebar:
        st.header("控制面板")
        indicator = st.radio("分析周期", ["今日", "5日", "10日"], index=0, horizontal=True)
        refresh_interval = st.slider("自动刷新间隔 (秒)", 60, 3600, 60, 60)
        return indicator, refresh_interval

def main_display(df):
    st.title("📊 资金流向热力图")
    st.caption(f"数据更新时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

    if not df.empty:
        st.plotly_chart(generate_heatmap(df), use_container_width=True)
    else:
        st.warning("⚠️ 数据获取失败，请检查网络连接")

import time

def auto_refresh_system(refresh_interval):
    time.sleep(refresh_interval)
    st.rerun()

def build_page():
    indicator, refresh_interval = sidebar_controls()
    df = process_data(indicator)
    main_display(df)
    auto_refresh_system(refresh_interval)